const { app, BrowserWindow, globalShortcut, ipcMain, dialog } = require('electron');
const path = require('node:path');
const {createPdf} = require('./renderAPI/createPdf')
const {printPdf} = require('./renderAPI/printPdf')

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      allowRunningInsecureContent: true,
      webSecurity: false
    },
  });

  // and load the index.html of the app.
  // mainWindow.loadURL('http://localhost:9528');
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {

      return {
        action: 'allow',
        overrideBrowserWindowOptions: {

          webPreferences: {
            allowRunningInsecureContent: true
          }
        }
      }
  })

  const ses = mainWindow.webContents.session

  function downloadFileToFolder( url, fileName, fileType) {
    mainWindow.webContents.downloadURL(url);
    mainWindow.webContents.session.once('will-download', (event, item, webContents) => {
      //设置保存路径
      const appPath = app.isPackaged ? path.dirname(app.getPath('exe')) : app.getAppPath();
      
      const filePath = path.join(appPath, '/download', `${fileName}`);
      item.setSavePath(filePath);
      // item.on('updated', (event, state) => {
      //   if (state === 'interrupted') {
      //     console.log('下载中断，可以继续');
      //   } else if (state === 'progressing') {
      //     if (item.isPaused()) {
      //       console.log('下载暂停');
      //     } else {
      //       console.log(`当前下载项目的接收字节${item.getReceivedBytes()}`);
      //       console.log(`下载完成百分比：${item.getReceivedBytes() / item.getTotalBytes() * 100}`);
      //     }
      //   }
      // });
      item.once('done', (event, state) => {
        if (state === 'completed') {
          // shell.openPath(filePath) //打开文件
        }
      })
    })
  }
  


  ipcMain.on('file-download',async  (event, url,filename)=>{
    // console.log(url, 'url');
    // console.log(filename, 'filename');
    downloadFileToFolder(url,filename);
  })

  ipcMain.on('file-create',async  (event, url,filename)=>{
    // console.log(url, 'url');
    // console.log(filename, 'filename');
    createPdf(url,filename);
  })

  globalShortcut.register('Alt+CommandOrControl+F9', () => {
    console.log('Electron loves global shortcuts!')
    mainWindow.webContents.send('picture-capture-event', { message: '采图' })
   

  })

  
  globalShortcut.register('F7', () => {
    console.log('Electron oves global shortcuts!')
    printPdf()

   

  })


};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();

  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
